package FillMythMetadataParentalRating;
use strict;

my $set_show_level;
my $show_level_1;
my $show_level_2;
my $show_level_3;
my $show_level_4;
my $default_show_level = 1;

sub init
{
	my $dbh = $_[0];

	my $sqlstat=qq {select data from settings where value = 'mythvideo.ParentalLevelFromRating'};
	my $sth = $dbh->prepare($sqlstat);
	$sth->execute();
	$sth->bind_columns( undef, \$set_show_level );

	$sth->fetch();

	if ($set_show_level ne 0)#should do it
	{
		print "Parental level support is enabled!\n";
		$sqlstat=qq {select data from settings where value = 'mythvideo.AutoR2PL1'};
		$sth = $dbh->prepare($sqlstat);
		$sth->execute();
		$sth->bind_columns( undef, \$show_level_1 );
		$sth->fetch();
		
		$sqlstat=qq {select data from settings where value = 'mythvideo.AutoR2PL2'};
		$sth = $dbh->prepare($sqlstat);
		$sth->execute();
		$sth->bind_columns( undef, \$show_level_2 );
		$sth->fetch();
		
		$sqlstat=qq {select data from settings where value = 'mythvideo.AutoR2PL3'};
		$sth = $dbh->prepare($sqlstat);
		$sth->execute();
		$sth->bind_columns( undef, \$show_level_3 );
		$sth->fetch();
		
		$sqlstat=qq {select data from settings where value = 'mythvideo.AutoR2PL4'};
		$sth = $dbh->prepare($sqlstat);
		$sth->execute();
		$sth->bind_columns( undef, \$show_level_4 );
		$sth->fetch();
		
		#fixing the regex from 'R:NC-17' to '^(R|NC-17)$'
		$show_level_1 =~ s/:/\x7C/g;
		$show_level_2 =~ s/:/\x7C/g;
		$show_level_3 =~ s/:/\x7C/g;
		$show_level_4 =~ s/:/\x7C/g;
		#prefix and postfix
		$show_level_1 = '^('.$show_level_1.')$';
		$show_level_2 = '^('.$show_level_2.')$';
		$show_level_3 = '^('.$show_level_3.')$';
		$show_level_4 = '^('.$show_level_4.')$';
		
		print 'Parental Level regex are:\nLevel 1: '.$show_level_1.'\nLevel 2: '.$show_level_2.'\nLevel 3: '.$show_level_3.'\nLevel 4: '.$show_level_4.'\n';
	}
	else
	{
		print "Parental level support is disabled.\n";
	}
	
	return $default_show_level;
}

sub parse_show_level
{
	my $rating_string = $_[0];
	if (($set_show_level eq 0) || (!$rating_string))
	{
		return 'showlevel';#this will force the re-assignment of whatever already stored in the database.
	}
	
	#In myth, levels 2, 3, and 4 requires passwords
	#Level 1 (the lowest) does not require password.
	if ($rating_string =~ m/($show_level_1)/i)
	{
		return 1;
	}
	if ($rating_string =~ m/($show_level_2)/i)
	{
		return 2;
	}
	if ($rating_string =~ m/($show_level_3)/i)
	{
		return 3;
	}
	if ($rating_string =~ m/($show_level_4)/i)
	{
		return 4;
	}
	
	return $default_show_level;
}

1;